package com.sinsz.common.util;

import com.sinsz.common.exception.ApiException;
import com.sinsz.common.exception.DefaultError;
import org.springframework.util.StringUtils;

import java.security.MessageDigest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 签名工具
 * @author chenjianbo
 */
public class SignUtils {

    /**
     * 签名工具
     * <p>
     *     SHA1
     * </p>
     * @param source    待签名串
     * @return          签名串
     */
    public synchronized static String signatureSha1(String source) {
        final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            final MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(source.getBytes("UTF-8"));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char[] buf = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 签名工具
     * <p>
     *     MD5
     * </p>
     * @param source    待签名串
     * @return          签名串
     */
    public synchronized static String signatureMd5(final String source) {
        final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8',
                '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            final MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(source.getBytes("UTF-8"));
            final byte[] md = mdInst.digest();
            final int j = md.length;
            final char[] str = new char[j * 2];
            int k = 0;
            for (final byte byte0 : md) {
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (final Exception e) {
            return "";
        }
    }

    /**
     * 编码签名
     * <p>
     *     签名方式：
     *     MD5/SHA1( （参数集合按字典排序并转换为字符串）+ （签名key） ) 并转换为大写。
     * </p>
     * @param params        参数集合
     * @param signKey       签名KEY
     * @param method        签名方式<p>默认MD5</p>
     * @return              签名密钥
     */
    public synchronized static String sign(List<String> params, String signKey, SignEnum method) {
        if (params == null
                || params.isEmpty()
                || StringUtils.isEmpty(signKey)) {
            throw new ApiException(DefaultError.SIGN_ERR_01);
        }
        //参数排序
        List<String> list = params.stream().sorted().collect(Collectors.toList());
        String paramStr = String.join("", list) + signKey;
        //处理默认签名方式
        method = method == null ? SignEnum.MD5 : method;
        return method.setSource(paramStr).toString();
    }

    /**
     * 验证签名
     * @param sign      原签名值
     * @param params    参数集合
     * @param signKey   签名KEY
     * @param method    签名方式
     * @return          是否签名校验通过
     */
    public synchronized static boolean checkSign(String sign, List<String> params, String signKey, SignEnum method) {
        if (StringUtils.isEmpty(sign)) {
            throw new ApiException(DefaultError.SIGN_ERR_02);
        }
        return sign.equals(SignUtils.sign(params, signKey, method));
    }

}
